package models

import play.api.db.slick.Profile

case class Good(id: Option[Long], name: String, price: Double, cost: Double)

trait GoodComponent { this: Profile => //<- step 1: you must add this "self-type"
  import profile.simple._ //<- step 2: then import the correct Table, ... from the profile

  class GoodsTable(tag: Tag) extends Table[Good](tag, "GOOD") {

    def id = column[Long]("id",O.PrimaryKey, O.AutoInc)
    def name = column[String]("name", O.NotNull)
    def price = column[Double]("price", O.NotNull)
    def cost = column[Double]("cost",O.NotNull)

    def * = (id.?, name, price, cost) <> (Good.tupled, Good.unapply _)
  }

  object GoodDB {
    import play.api.db.slick.Config.driver.simple._

    val Goods = TableQuery[GoodsTable]

    def findById(id: Long)(implicit s: Session): Option[Good] =
      Goods.filter(_.id === id).firstOption

    def count(implicit s: Session): Int =
      Query(Goods.length).first

    def count(filter: String)(implicit s: Session): Int =
      Query(Goods.filter(_.name.toLowerCase like filter.toLowerCase).length).first

    def list(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%")(implicit s: Session): Page[Good] = {

      val offset = pageSize * page
      val query =
        (for {
          good <- Goods
          if good.name.toLowerCase like filter.toLowerCase()
        } yield good)
          .drop(offset)
          .take(pageSize)

      val totalRows = count(filter)
      val result = query.list

      Page(result, page, offset, totalRows)
    }

    def insert(good: Good)(implicit s: Session) {
      Goods.insert(good)
    }


    def update(id: Long, good: Good)(implicit s: Session) {
      val computerToUpdate: Good = good.copy(Some(id))
      Goods.filter(_.id === id).update(computerToUpdate)
    }

//    def delete(id: Long)(implicit s: Session) {
//      Goods.filter(_.id === id).delete
//    }
  }

}

